#!/bin/bash

# Build Drawpile stable branch AppImage
# Run inside a CentOS 6 docker image.
# This script is partially based on https://github.com/probonopd/AppImages/blob/master/recipes/subsurface/Recipe

set -e
set -x

. /opt/rh/devtoolset-3/enable

SRCDIR=/Drawpile
WORKDIR=/work
BUILDDIR=/build
APPDIR=/Drawpile.AppDir
APPIMGKIT=/AppImageKit-master

# Copy source code to work dir and apply appimage specific patches
mkdir -p $WORKDIR
cp -r ${SRCDIR}/* $WORKDIR
cd $WORKDIR
git apply pkg/appimage/appimage-client.patch

# Build the client
mkdir -p $BUILDDIR
mkdir -p $APPDIR
cd $BUILDDIR
cmake3 $WORKDIR -DSERVER=OFF -DINSTALL_DOC=OFF -DKIS_TABLET=ON -DCMAKE_INSTALL_PREFIX=$APPDIR/usr
make -j5
make install


# Construct AppDir bundle
cd $APPDIR

cp $APPIMGKIT/AppRun .
chmod a+x AppRun


# Copy libraries
mkdir -p usr/lib/qt5/plugins/platforms
cd usr
ln -s lib lib64
cd ..

cp -r /usr/lib64/qt5/plugins/{audio,generic,iconengines,imageformats,platforminputcontexts} usr/lib/qt5/plugins
cp /usr/lib64/qt5/plugins/platforms/libqxcb.so usr/lib/qt5/plugins/platforms

ldd usr/bin/drawpile | grep "=>" | awk '{print $3}' | xargs -I '{}' cp -vL '{}' ./usr/lib || true
ldd usr/lib/qt5/plugins/platforms/libqxcb.so | grep "=>" | awk '{print $3}' | xargs -I '{}' cp -vL '{}' ./usr/lib || true


cd usr/ ; find . -type f -exec sed -i -e 's|/usr/lib|././/lib|g' {} \; ; cd ..

# Remove blacklisted libs
BLACKLISTED_FILES=$(sed '/^\s*$/d' $SRCDIR/pkg/appimage/excludelist | sed '/^#.*$/d')
for FILE in $BLACKLISTED_FILES ; do
	FOUND=$(find . -type f -name "${FILE}" 2>/dev/null)
	if [ ! -z "$FOUND" ] ; then
		echo "Deleting blacklisted ${FOUND}"
		rm -f "${FOUND}"
	fi
done


# Copy desktop stuff
cp $SRCDIR/desktop/drawpile.desktop .

ICONDIR=usr/share/icons/hicolor
mkdir -p $ICONDIR/16x16/apps
cp $SRCDIR/desktop/drawpile-16x16.png $ICONDIR/16x16/apps/drawpile.png
mkdir -p $ICONDIR/32x32/apps
cp $SRCDIR/desktop/drawpile-32x32.png $ICONDIR/32x32/apps/drawpile.png
mkdir -p $ICONDIR/48x48/apps
cp $SRCDIR/desktop/drawpile-48x48.png $ICONDIR/48x48/apps/drawpile.png
mkdir -p $ICONDIR/64x64/apps
cp $SRCDIR/desktop/drawpile-64x64.png $ICONDIR/64x64/apps/drawpile.png
mkdir -p $ICONDIR/128x128/apps
cp $SRCDIR/desktop/drawpile-128x128.png $ICONDIR/128x128/apps/drawpile.png
mkdir -p $ICONDIR/scalable/apps
cp $SRCDIR/desktop/drawpile.svg $ICONDIR/scalable/apps/drawpile.svg
cp $SRCDIR/desktop/drawpile.svg $APPDIR


# Build Appimage

cd /Drawpile
VERSION=$(ls $APPDIR/usr/bin/drawpile-* | cut -d - -f 2-)
APPIMAGE="Drawpile-$VERSION.AppImage"

rm -f /out/$APPIMAGE
$APPIMGKIT/AppImageAssistant.AppDir/package $APPDIR /out/$APPIMAGE

